import { Button, Text, View } from 'native-base';
import React, { useState } from 'react';
import { Modal, StyleSheet } from 'react-native';
import AntDesign from 'react-native-vector-icons/AntDesign';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import { CommonStyle } from '../common/commonStyle.ts';
import AudioRecorderClass from '../utils/AudioRecorderClass.ts';
import Tools from '../utils/Tools.ts';
import ProgressBar from './ProgressBar.tsx';
import { useDispatch } from 'react-redux';
import { AppDispatch } from '../redux/store.ts';
import { updateRecording } from '../redux/reducers/app.ts';

let recordingInstance: any = null;

const RecordingModal = () => {
  const [visible, setVisible] = useState(false); // 控制弹框的可见性
  const [recorder] = useState(new AudioRecorderClass());
  const [recordingData, setRecordingData] = useState<{ filePath: string | null; duration: number }>({ filePath: null, duration: 0 });
  const [text, setText] = useState('发送订单');
  const [play, setPlay] = useState<boolean>(false);
  const [playProgress, setPlayProgress] = useState<number>(0);
  const dispatch = useDispatch<AppDispatch>();

  const show = async (text: string = '发送订单') => {
    setVisible(true);
    setText(text);
    await recorder.startRecording((filePath, duration) => {
      if (duration > 30 * 1000) {
        handleStopRecord();
      } else {
        setRecordingData((prevState) => ({ ...prevState, duration }));
      }
    });
  };

  const hide = async () => {
    await recorder.stopRecording();
    setVisible(false);
    setRecordingData({ filePath: null, duration: 0 });
  };

  // 停止录音
  const handleStopRecord = async () => {
    const result = await recorder.stopRecording();
    dispatch(updateRecording(result.filePath || ''));
    setRecordingData({ ...result });
  };

  // 播放录音文件
  const handlePlayRecorderFile = async () => {
    setPlay(true);
    await recorder.playRecording(
      recordingData.filePath!,
      (hasComplete) => {
        hasComplete && setPlay(false);
      },
      (progress) => {
        setPlayProgress(progress);
      },
    );
  };

  // 提交录音
  const handleSubmit = () => {
    if (text === '发送订单') {
      console.log(123);
      return;
    }
    hide();
  };

  recordingInstance = { show, hide };

  return (
    <Modal transparent={true} visible={visible} animationType="fade" onRequestClose={() => hide()}>
      <View style={styles.overlay}>
        <View style={styles.container}>
          <View style={styles.top}>
            <AntDesign size={26} name={'closecircleo'} onPress={() => hide()} />
          </View>
          {recordingData.filePath && (
            <View style={styles.content}>
              {!play && <AntDesign name={'play'} size={98} color={'#f18311'} style={{ marginBottom: 100 }} onPress={handlePlayRecorderFile} />}
              {play && (
                <AntDesign
                  name={'pausecircle'}
                  size={98}
                  color={'#f18311'}
                  style={{ marginBottom: 40 }}
                  onPress={async () => {
                    await recorder.stopPlaying();
                    setPlay(false);
                  }}
                />
              )}
              {play && <ProgressBar customStyles={{ marginBottom: 48 }} totalValue={recordingData.duration} progressValue={playProgress} height={8} backgroundColor="#ddd" showPercentage={false} />}
              <Button bg={CommonStyle.mainColor} width={'100%'} borderRadius={8} _pressed={{ bg: CommonStyle.btnSelectMainColor }} onPress={handleSubmit}>
                {text}
              </Button>
            </View>
          )}
          {!recordingData.filePath && (
            <View style={styles.content}>
              <FontAwesome name={'microphone'} size={98} color={'#f18311'} style={{ marginHorizontal: 4 }} />
              <View w={'100%'}>
                <Text fontSize={12} color={'#f18311'} fontWeight={'bold'} textAlign={'center'}>
                  录音中...
                </Text>
              </View>
              <View w={'100%'}>
                <Text fontSize={18} color={'#f18311'} fontWeight={'bold'} textAlign={'center'} mt={4}>
                  {Tools.millisecondConversionTimeFormat(recordingData.duration)}
                </Text>
              </View>
              <ProgressBar customStyles={{ marginTop: 8 }} totalValue={30 * 1000} progressValue={recordingData.duration} height={8} backgroundColor="#ddd" showPercentage={false} />

              <Button bg={CommonStyle.mainColor} width={'100%'} borderRadius={8} _pressed={{ bg: CommonStyle.btnSelectMainColor }} marginTop={'8'} onPress={handleStopRecord}>
                停止录音
              </Button>
            </View>
          )}
        </View>
      </View>
    </Modal>
  );
};

/**
 * 录音中
 */
export const Recording = {
  show: (text?: string) => {
    if (recordingInstance) {
      recordingInstance.show(text);
    }
  },
  hide: () => {
    if (recordingInstance) {
      recordingInstance.hide();
    }
  },
};

const styles = StyleSheet.create({
  overlay: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0,0,0,0.2)' },
  container: { width: '95%', height: 320, backgroundColor: 'rgb(240,240,240)', borderRadius: 10, padding: 16 },
  top: { width: '100%', flexDirection: 'row', justifyContent: 'flex-end' },
  content: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', flexWrap: 'wrap' },
});

export default RecordingModal;
